package com.codeant.bikeindicatorapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.allen.library.SuperTextView;
import com.allen.library.shape.ShapeLinearLayout;
import com.codeant.bikeindicatorapplication.tools.ClickFeedbackHelper;
import com.codeant.bikeindicatorapplication.tools.FlashLightHelper;
import com.codeant.bikeindicatorapplication.tools.InformationFlowHelper;
import com.codeant.bikeindicatorapplication.tools.MyBroadcastReceiver;
import com.codeant.bikeindicatorapplication.tools.PermissionHelper;
import com.codeant.bikeindicatorapplication.tools.PublicVariables;
import com.codeant.bikeindicatorapplication.tools.ScreenSizeHelper;
import com.codeant.bikeindicatorapplication.tools.SharedPreferencesHelper;
import com.codeant.bikeindicatorapplication.tools.SingleToast;
import com.codeant.bikeindicatorapplication.tools.SoundHelper;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView2;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements SensorEventListener, PermissionHelper.PermissionCallbacks {

    private final String TAG = "MainActivity";

    //各个控件布局
    private SuperButton statusbar_sbtn;//调节上边距用的控件
    private SuperTextView speed_stv;//速度文本框
    private SuperTextView setting_stv;//设置按钮
    private SuperTextView ble_status_stv;//蓝牙状态显示（配对按钮）
    private SuperTextView ble_connect_stv;//蓝牙连接按钮
    private SuperTextView auto_mode_stv;//自动模式开关
    private SuperTextView wake_screen_stv;//屏幕常亮开关
    private ShapeLinearLayout btn_reset;//复位按钮
    private ShapeLinearLayout btn_stop;//刹车按钮
    private QMUIRadiusImageView2 btn_left;//左转按钮
    private QMUIRadiusImageView2 btn_right;//右转按钮
    private QMUIRadiusImageView2 btn_honking;//鸣笛按钮

    private TextView test_tv;//临时显示加速度数据的文本框

    private ClickFeedbackHelper clickFeedbackHelper;//震动反馈实例

    private int STATUS_BLE = 0;//蓝牙的几种状态：未打开0 未连接1 连接正常2 未知异常3
    private BluetoothAdapter btAdapter = null;//系统的蓝牙适配器
    ArrayList<BluetoothDevice> deviceList;//记录已连接设备（不只是已配对）

    //具体发送指令相关
//    private final String DEVICE_ADDRESS="98:D3:31:FD:BE:80";
    private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");//Serial Port Service ID
    private BluetoothDevice device;
    private BluetoothSocket socket=null;
    private OutputStream outputStream=null;
    private InputStream inputStream=null;
    boolean targetDeviceConnected=false;//标记指定设备是否连接成功
    Thread thread;
    byte buffer[];
    int bufferPosition;
    boolean stopThread;

    private int CURRENT_SPEED = 0;//实时行驶速度

    ScreenSizeHelper screenSizeHelper;//屏幕尺寸工具（对应上方调节上边距用）

    SensorManager sensorManager;//加速度传感器管理器
    Sensor sensor = null;//加速度传感器实例
    StringBuffer ACCELEROMETER_DATA;//加速度数据
    float ACCELEROMETER_X = 0;//X加速度数据
    float ACCELEROMETER_Y = 0;//Y加速度数据
    float ACCELEROMETER_Z = 0;//Z加速度数据
    float ACCEL_X = 0;//加速度竖屏方向初始值
    float ACCEL_Y = 0;//加速度横屏方向初始值
    float ACCEL_EXTENT = 0;//转弯幅度初始值

    private final int PERMS_REQUEST_CODE = 200;
    InformationFlowHelper informationFlowHelper;//速度获取

    private Boolean FLAG_AUTO_MODE= false;//记录“自动模式”是否已打开
    private int current_turn_status = 6;//记录当前指令状态，6熄灭，7刹车，8左转，9右转

    PublicVariables pubVari = new PublicVariables();//一些公有变量
    SharedPreferencesHelper sph = new SharedPreferencesHelper();//信息存储工具
    Boolean layout_land, layout_left, layout_right;//横屏模式、左右手布局的记录信息

    private int TAG_GPS_OR_AIR = 0;//0表示GPS，1表示空气质量

    private Boolean FLAG_HONKING_PLUS = false;//记录“增强鸣笛”是否打开
    SoundHelper sh = null;//音频音效播放工具
    FlashLightHelper flp = null;//手电筒工具

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //读取设置信息
        sph.initSP(MainActivity.this);//记得初始化
        layout_land = sph.getSP_boolean("BI","land_mode",false);//横屏状态
        layout_left = sph.getSP_boolean("BI","left_mode",false);//靠左状态
        layout_right = sph.getSP_boolean("BI","right_mode",false);//靠右状态

        super.onCreate(savedInstanceState);
        //根据设置信息选取竖横屏、左右手布局
        if (layout_land){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//请求横屏
            if (layout_left){
                setContentView(R.layout.activity_main_land_left);//靠左布局
                LinearLayout l_con = (LinearLayout) findViewById(R.id.controller_linear);
                l_con.setGravity(Gravity.LEFT);
            }else if(layout_right){
                setContentView(R.layout.activity_main_land);//靠右布局
                LinearLayout l_con = (LinearLayout) findViewById(R.id.controller_linear);
                l_con.setGravity(Gravity.RIGHT);
            }else {
                setContentView(R.layout.activity_main_land);//普通横屏
            }
        }else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//请求竖屏
            setContentView(R.layout.activity_main);
            if (layout_left){
                LinearLayout l_con = (LinearLayout) findViewById(R.id.controller_linear);
                l_con.setGravity(Gravity.LEFT);
            }else if(layout_right){
                LinearLayout l_con = (LinearLayout) findViewById(R.id.controller_linear);
                l_con.setGravity(Gravity.RIGHT);
            }else {
//                l_controller.setGravity(Gravity.CENTER);
            }
        }

        //权限申请
        PermissionHelper.requestPermissions(
                this,
                PERMS_REQUEST_CODE,
                pubVari.getPerms());

        initBle();
        initWidgets();
        initGps();

        //启动进程保活
//        final Intent intent = new Intent(MainActivity.this, BackGroundService.class);
//        startService(intent);

        //定义前台服务的默认样式。即标题、描述和图标
//        ForegroundNotification foregroundNotification = new ForegroundNotification("测试","描述", R.drawable.app_logo,
//                //定义前台服务的通知点击事件
//                new ForegroundNotificationClickListener() {
//
//                    @Override
//                    public void foregroundNotificationClick(Context context, Intent intent) {
//                    }
//                });
//        //启动保活服务
//        KeepLive.startWork(this.getApplication(), KeepLive.RunMode.ENERGY, foregroundNotification,
//                //你需要保活的服务，如socket连接、定时任务等，建议不用匿名内部类的方式在这里写
//                new KeepLiveService() {
//                    /**
//                     * 运行中
//                     * 由于服务可能会多次自动启动，该方法可能重复调用
//                     */
//                    @Override
//                    public void onWorking() {
//
//                    }
//                    /**
//                     * 服务终止
//                     * 由于服务可能会被多次终止，该方法可能重复调用，需同onWorking配套使用，如注册和注销broadcast
//                     */
//                    @Override
//                    public void onStop() {
//
//                    }
//                }
//        );
    }

    public void initBle(){
        //因为SplashActivity已经检测了蓝牙硬件，所以无需再检测
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        //获取已配对设备
//        Set<BluetoothDevice> bondedDevices = btAdapter.getBondedDevices();
//        for(BluetoothDevice device : bondedDevices){
//            if(device.getName().equals("HC05")){
//                Log.i(TAG,"bonded:" + device.getName() + "\n" + device.getAddress() + "\n" + device.getUuids());
//            }
//        }
        //获取已连接设备
        deviceList = getConnectionDevices(btAdapter);
    }

    public void initGps(){
        //监听GPS的开启状态的广播接收器
        IntentFilter gpsStateFilter = new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION);
        this.registerReceiver(gpsReceiver,gpsStateFilter);

        //监听蓝牙状态的广播接收器
        IntentFilter btStateFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        btStateFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        btStateFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        btStateFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        this.registerReceiver(bleReceiver,btStateFilter);
        Log.i(TAG,"this device:" + btAdapter.getName() + "\n" +
                btAdapter.getAddress() + "\n" +
                String.valueOf(btAdapter.getBondedDevices()));

        //加速度传感器管理者
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        //加速度传感器实例
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }

    protected void onResume(){
        super.onResume();
        //添加（注册）加速度监听器
        if(sensorManager != null){
            sensorManager.registerListener(
                    (SensorEventListener) this,
                    sensor,SensorManager.SENSOR_DELAY_UI);

//            sensorManager.registerListener((SensorListener) this, SensorManager.SENSOR_ORIENTATION
//                            | SensorManager.SENSOR_ACCELEROMETER,
//                    200000);//设置采样率
        }
    }

    protected void onPause(){
        //解除加速度传感器的监听
        if(sensorManager != null){
            sensorManager.unregisterListener((SensorEventListener) this,sensor);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        try {
            //解除蓝牙和传感器的监听
            if(bleReceiver != null){
                this.unregisterReceiver(bleReceiver);
            }
            if(sensorManager != null){
                sensorManager.unregisterListener((SensorEventListener) this,sensor);
            }
            //关闭输入输出流
            if (inputStream!=null){
                inputStream.close();
            }
            if (outputStream!=null){
                outputStream.close();
            }
            if (socket!=null){
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        sh.release();//释放音频播放资源
        //关闭进程保活
        final Intent intent = new Intent(MainActivity.this, BackGroundService.class);
        stopService(intent);
        super.onDestroy();
    }

    //初始化各个组件布局、监听事件等
    private void initWidgets(){
        statusbar_sbtn = (SuperButton) findViewById(R.id.statusbar_sbtn_main);
        speed_stv = (SuperTextView) findViewById(R.id.speed_stv_main);
        setting_stv = (SuperTextView) findViewById(R.id.setting_stv_main);
        ble_status_stv = (SuperTextView) findViewById(R.id.ble_status_stv_main);
        ble_connect_stv = (SuperTextView) findViewById(R.id.ble_connect_stv_main);
        auto_mode_stv = (SuperTextView) findViewById(R.id.auto_mode_stv_main);
        wake_screen_stv = (SuperTextView) findViewById(R.id.wake_screen_stv_main);
        btn_reset = (ShapeLinearLayout) findViewById(R.id.linear1_0_main);
        btn_stop = (ShapeLinearLayout) findViewById(R.id.linear1_1_main);
        btn_left = (QMUIRadiusImageView2) findViewById(R.id.left_main);
        btn_right = (QMUIRadiusImageView2) findViewById(R.id.right_main);
        btn_honking = (QMUIRadiusImageView2) findViewById(R.id.honking_main);

        speed_stv.setOnClickListener(new ClickListeners());
        speed_stv.setTag(pubVari.TAG_SBTN_MSG);

        setting_stv.setOnClickListener(new ClickListeners());
        setting_stv.setTag(pubVari.TAG_SBTN_SETTING);

        ble_status_stv.setOnClickListener(new ClickListeners());
        ble_status_stv.setTag(pubVari.TAG_SBTN_BLE_STATUS);

        ble_connect_stv.setOnClickListener(new ClickListeners());
        ble_connect_stv.setTag(pubVari.TAG_SBTN_BLE_CONNECT);

        btn_reset.setOnClickListener(new ClickListeners());
        btn_reset.setTag(pubVari.TAG_RESET);

        btn_stop.setOnClickListener(new ClickListeners());
        btn_stop.setTag(pubVari.TAG_STOP);

        btn_left.setOnClickListener(new ClickListeners());
        btn_left.setOnTouchListener(new OnTouchListeners());
        btn_left.setTag(pubVari.TAG_LEFT);

        btn_right.setOnClickListener(new ClickListeners());
        btn_right.setOnTouchListener(new OnTouchListeners());
        btn_right.setTag(pubVari.TAG_RIGHT);

        btn_honking.setOnClickListener(new ClickListeners());
        btn_honking.setOnTouchListener(new OnTouchListeners());
        btn_honking.setTag(pubVari.TAG_HONKING);

        auto_mode_stv.setOnClickListener(new ClickListeners());
        auto_mode_stv.setTag(pubVari.TAG_SBTN_AUTO_MODE);

        wake_screen_stv.setOnClickListener(new ClickListeners());
        wake_screen_stv.setTag(pubVari.TAG_SBTN_WAKE_SCREEN);

        test_tv = (TextView) findViewById(R.id.test_tv_main);

        //加载增强鸣笛的设置信息
        FLAG_HONKING_PLUS = sph.getSP_boolean("BI","honking_plus",false);
        sh = new SoundHelper();
        sh.init(MainActivity.this);

        //左上角速度显示相关
        informationFlowHelper = new InformationFlowHelper();
        informationFlowHelper.init(speed_stv, MainActivity.this, MainActivity.this);
        informationFlowHelper.getCurrentSpeed();

        //闪光灯服务
        flp = new FlashLightHelper();
        flp.init(MainActivity.this);

        clickFeedbackHelper = new ClickFeedbackHelper();

        screenSizeHelper = new ScreenSizeHelper();
        screenSizeHelper.getStatusBarHeight(MainActivity.this);
        // 如果成功获取到状态栏高度（≠-1），再设置控件高度用来保持一定的上边距，否则就使用原来的20dp
        if(screenSizeHelper.statusBarHeight_pixel != -1){
            statusbar_sbtn.setHeight(screenSizeHelper.statusBarHeight_pixel);
        }

        //初始化自动模式的checkBox相关点击事件等
        FLAG_AUTO_MODE= sph.getSP_boolean("BI","auto_mode_status",false);
        //根据已有的设置信息来设置对应开关的状态
        if(FLAG_AUTO_MODE){
            auto_mode_stv.setCbChecked(true);
        }
        auto_mode_stv.setCheckBoxCheckedChangeListener(new SuperTextView.OnCheckBoxCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.i(TAG,String.valueOf(isChecked));
                //让所有可点击事件都带有震动反馈（线性马达或者普通震动）
                clickFeedbackHelper.feedback(buttonView, MainActivity.this);
                //按钮的checkBox状态改变后及时写入存储
                if (isChecked){
                    sph.saveSP_boolean("BI","auto_mode_status",true);
                    FLAG_AUTO_MODE= true;
                }else{
                    sph.saveSP_boolean("BI","auto_mode_status",false);
                    FLAG_AUTO_MODE= false;
                }
            }
        });

        //屏幕常亮的开关（默认打开）
        wake_screen_stv.setSwitchIsChecked(true);
        wake_screen_stv.setSwitchCheckedChangeListener(new SuperTextView.OnSwitchCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //让所有可点击事件都带有震动反馈（线性马达或者普通震动）
                clickFeedbackHelper.feedback(buttonView, MainActivity.this);
                if (isChecked){
                    SingleToast.getInstance(MainActivity.this).show("屏幕常亮已开启");
                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                }else{
                    SingleToast.getInstance(MainActivity.this).show("屏幕常亮已关闭");
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                }
            }
        });

        //左右切换PM2.5和行驶速度
        speed_stv.setRightImageViewClickListener(new SuperTextView.OnRightImageViewClickListener() {
            @Override
            public void onClickListener(ImageView imageView) {
                clickFeedbackHelper.feedback(imageView, MainActivity.this);
                //0表示GPS，1表示空气质量
                if (TAG_GPS_OR_AIR == 0){
                    informationFlowHelper.onGpsStop();
                    informationFlowHelper.updateAir();
                    TAG_GPS_OR_AIR = 1;
                }else{
                    informationFlowHelper.init(speed_stv, MainActivity.this, MainActivity.this);
                    informationFlowHelper.getCurrentSpeed();
                    TAG_GPS_OR_AIR = 0;
                }
            }
        });
        speed_stv.setLeftImageViewClickListener(new SuperTextView.OnLeftImageViewClickListener() {
            @Override
            public void onClickListener(ImageView imageView) {
                clickFeedbackHelper.feedback(imageView, MainActivity.this);
                //0表示GPS，1表示空气质量
                if (TAG_GPS_OR_AIR == 0){
                    informationFlowHelper.onGpsStop();
                    informationFlowHelper.updateAir();
                    TAG_GPS_OR_AIR = 1;
                }else{
                    informationFlowHelper.init(speed_stv, MainActivity.this, MainActivity.this);
                    informationFlowHelper.getCurrentSpeed();
                    TAG_GPS_OR_AIR = 0;
                }
            }
        });

        //获取默认的加速度初始值(初始方向默认为0，转弯幅度为±1.8)
        ACCEL_X = sph.getSP_float("BI","ACCEL_X","0");
        ACCEL_Y = sph.getSP_float("BI","ACCEL_Y","0");
        ACCEL_EXTENT = sph.getSP_float("BI","ACCEL_EXTENT","1.8");
    }

    //主要控件的点击事件1
    private class ClickListeners implements View.OnClickListener{
        @Override
        public void onClick(View v){
            int key = 0;
            if(v.getTag()!=null){
                key = (Integer) v.getTag();
            }
            if (key != 101 && key != 102 && key != 105){//避免鸣笛按钮多重振动
                //让所有可点击事件都带有震动反馈（线性马达或者普通震动）
                clickFeedbackHelper.feedback(v, MainActivity.this);
            }
            switch (key){
                case 1://设置
                    Intent intent = new Intent(MainActivity.this,SettingActivity.class);
                    intent.putExtra("statusBarHeight_pixel", screenSizeHelper.statusBarHeight_pixel); // 将状态栏尺寸传递给设置界面
                    startActivity(intent);
                    break;
                case 105://鸣笛
//                    send("05");
                    break;
                case 104://复位
                    send("04");
                    sh.stop();
                    flp.fickOff();
                    break;
                case 103://停
                    send("03");
                    break;
                case 101://左转
//                    send("01");
                    break;
                case 102://右转
//                    send("02");
                    break;
                case 5://蓝牙配对（直接调用系统设置）
                    if(STATUS_BLE == 0){//蓝牙未打开
                        SingleToast.getInstance(MainActivity.this).show("请打开蓝牙");
//                        startActivity(
//                                new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                    }else if(STATUS_BLE == 1){//蓝牙未连接
                        SingleToast.getInstance(MainActivity.this).show("请连接对应的设备\n一般为“HC05”");
                    }else if(STATUS_BLE == 2){//一切正常
                        SingleToast.getInstance(MainActivity.this).show("蓝牙正常，无需操作");
                    }else if(STATUS_BLE == 3){//设备异常（如设备连接错了）
                        SingleToast.getInstance(MainActivity.this).show("蓝牙设备有误，请重新连接\n一般为“HC05”");
                    }
                    startActivity(
                            new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                    break;
                case 10://蓝牙连接
                    //若蓝牙未打开
                    if (!btAdapter.isEnabled()){
                        SingleToast.getInstance(MainActivity.this).show("蓝牙未打开或无已配对设备\n请先打开蓝牙或将设备配对");
                        break;
                    }
                    // 1.绑定已配对设备数据
                    Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
                    List<BluetoothDevice> devices_list = new ArrayList<>(devices);
                    ArrayList<String> listItems = new ArrayList<>();
                    String[] listItems_1;
                    for(BluetoothDevice device:devices){
                        listItems.add(device.getName());
                    }
                    listItems_1 = new String[listItems.size()];
                    listItems.toArray(listItems_1);
                    List<String> data = new ArrayList<>();
                    Collections.addAll(data, listItems_1);
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                            MainActivity.this,
                            R.layout.simple_list_item,
                            data);
                    //若蓝牙已连接，提示是否要先断开连接
                    if (targetDeviceConnected){
                        new QMUIDialog.MessageDialogBuilder(MainActivity.this)
                                .setTitle("提示")
                                .setMessage("已连接" + device.getName() + "，需要断开当前设备并连接其他设备吗？")
                                .addAction("取消", new QMUIDialogAction.ActionListener() {
                                    @Override
                                    public void onClick(QMUIDialog dialog, int index) {
                                        clickFeedbackHelper.feedback(v, MainActivity.this);
                                        dialog.dismiss();
                                    }
                                })
                                .addAction("确定", new QMUIDialogAction.ActionListener() {
                                    @Override
                                    public void onClick(QMUIDialog dialog, int index) {
                                        clickFeedbackHelper.feedback(v, MainActivity.this);
                                        //断开输入输出流
                                        stopThread = true;
                                        try {
                                            if (inputStream!=null){
                                                inputStream.close();
                                            }
                                            if (outputStream!=null){
                                                outputStream.close();
                                            }
                                            if (socket!=null){
                                                socket.close();
                                            }
                                            targetDeviceConnected=false;
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                        //关闭当前提示框
                                        Log.d(TAG, "断开");
                                        dialog.dismiss();
                                        // 2.设备列表弹框的生成
                                        QMUIPopups.listPopup(MainActivity.this,
                                                QMUIDisplayHelper.dp2px(MainActivity.this, 250),
                                                QMUIDisplayHelper.dp2px(MainActivity.this, 300),
                                                adapter,
                                                new AdapterView.OnItemClickListener() {
                                                    @Override
                                                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                                        //让所有可点击事件都带有震动反馈（线性马达或者普通震动）
                                                        clickFeedbackHelper.feedback(view, MainActivity.this);
                                                        SingleToast.getInstance(MainActivity.this).show("连接"+devices_list.get(position).getName()+"中");
                                                        start(devices_list.get(position).getAddress());
                                                    }
                                                })
                                                .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                                                .preferredDirection(QMUIPopup.DIRECTION_TOP)
                                                .shadow(true)
                                                .arrow(true)
                                                .dimAmount(0.6f)
                                                .shadowElevation(10,5)
                                                .edgeProtection(QMUIDisplayHelper.dp2px(MainActivity.this, 10))
                                                .offsetYIfTop(QMUIDisplayHelper.dp2px(MainActivity.this, 5))
                                                .skinManager(QMUISkinManager.defaultInstance(MainActivity.this))
                                                .show(v);
                                    }
                                })
                                .show();
                        break;
                    }else{
                        // 2.设备列表弹框的生成
                        QMUIPopups.listPopup(MainActivity.this,
                                QMUIDisplayHelper.dp2px(MainActivity.this, 250),
                                QMUIDisplayHelper.dp2px(MainActivity.this, 300),
                                adapter,
                                new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                        //让所有可点击事件都带有震动反馈（线性马达或者普通震动）
                                        clickFeedbackHelper.feedback(view, MainActivity.this);
                                        SingleToast.getInstance(MainActivity.this).show("连接"+devices_list.get(position).getName()+"中");
                                        start(devices_list.get(position).getAddress());
                                    }
                                })
                                .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                                .preferredDirection(QMUIPopup.DIRECTION_TOP)
                                .shadow(true)
                                .arrow(true)
                                .dimAmount(0.6f)
                                .shadowElevation(10,5)
                                .edgeProtection(QMUIDisplayHelper.dp2px(MainActivity.this, 10))
                                .offsetYIfTop(QMUIDisplayHelper.dp2px(MainActivity.this, 5))
                                .skinManager(QMUISkinManager.defaultInstance(MainActivity.this))
                                .show(v);
                        break;
                    }
                case 15://自动模式
                    break;
                case 20://屏幕常亮
                    break;
                case 25://速度、pm2.5信息栏
                    break;
                default:
                    break;
            }
        }
    }
    //主要控件的点击事件2（触摸事件，鸣笛功能需要）
    private class OnTouchListeners implements View.OnTouchListener{
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            int key = 0;
            if(view.getTag()!=null){
                key = (Integer) view.getTag();
            }

            if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                //让所有可点击事件都带有震动反馈（线性马达或者普通震动）
                clickFeedbackHelper.feedback(view, MainActivity.this);
                switch (key){
                    case 101://左转
                        btn_left.setImageResource(R.drawable.icon_left_1);
                        send("01");
                        break;
                    case 102://右转
                        btn_right.setImageResource(R.drawable.icon_right_1);
                        send("02");
                        break;
                    case 105://鸣笛
                        send("05");
                        btn_honking.setImageResource(R.drawable.icon_honking_1);
                        if (FLAG_HONKING_PLUS){
                            Log.i(TAG,"增强鸣笛");
                            sh.play(true);//手机鸣笛
//                            flp.open();
                            flp.fickOn();
                        }
                        break;
                    default:
                        break;
                }
            }else if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                //让所有可点击事件都带有震动反馈（线性马达或者普通震动）
                clickFeedbackHelper.feedback(view, MainActivity.this);
                switch (key){
                    case 101://左转
                        btn_left.setImageResource(R.drawable.icon_left);
                        break;
                    case 102://右转
                        btn_right.setImageResource(R.drawable.icon_right);
                        break;
                    case 105://关闭鸣笛（切换状态即可）
                        send("04");//用其他指令覆盖旧指令即可
                        btn_honking.setImageResource(R.drawable.icon_honking);
                        sh.stop();//发送04时同时关闭闪光灯和铃声
                        flp.fickOff();
                        break;
                    default:
                        break;
                }
            }
            return false;
        }
    }

    //蓝牙状态的广播接收器，兼顾改变蓝牙状态控件的提示信息
    public MyBroadcastReceiver bleReceiver = new MyBroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            super.onReceive(context, intent);

            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            switch (action){
                case BluetoothDevice.ACTION_ACL_CONNECTED:
                    Log.i(TAG , "\n蓝牙设备:" + device.getName() + "已连接" +
                            "\nmac地址:" + device.getAddress() +
                            "\nuuid:" + device.getUuids() );
                    SingleToast.getInstance(MainActivity.this).show("蓝牙设备:" + device.getName() + "已连接");
                    ble_connect_stv.setCenterString(device.getName().substring(0,4) + "…");//更新连接状态（显示设备名）
                    STATUS_BLE = 2;//蓝牙已连接
                    break;
                case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                    Log.i(TAG  , "蓝牙设备:" + device.getName() + "断开连接" );
                    SingleToast.getInstance(MainActivity.this).show("蓝牙设备:" + device.getName() + "断开连接");
                    ble_connect_stv.setCenterString("未连接");//更新连接状态
                    STATUS_BLE = 1;//蓝牙未连接
                    break;
                //上面的两个链接监听，其实也可以BluetoothAdapter实现，修改状态码即可
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    switch (blueState){
                        case BluetoothAdapter.STATE_OFF:
                            Log.i(TAG, "蓝牙关闭");
                            SingleToast.getInstance(MainActivity.this).show("蓝牙已关闭");
                            ble_connect_stv.setCenterString("蓝牙关闭");
                            STATUS_BLE = 0;//蓝牙未打开
                            break;
                        case BluetoothAdapter.STATE_ON:
                            Log.i(TAG, "蓝牙打开");
                            SingleToast.getInstance(MainActivity.this).show("蓝牙已打开");
                            ble_connect_stv.setCenterString("蓝牙打开");
                            STATUS_BLE = 1;//蓝牙未连接
                            break;
                    }
                    break;
                default:
                    Log.i(TAG, "蓝牙广播接收");
                    break;
            }
        }
    };

    //GPS状态的广播接收器
    public MyBroadcastReceiver gpsReceiver = new MyBroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            super.onReceive(context, intent);
            String action = intent.getAction();
            switch (action){
                case "android.location.PROVIDERS_CHANGED":
                    SingleToast.getInstance(MainActivity.this).show("GPS已打开");
                    break;
                case "not in android.location.PROVIDERS_CHANGED":
                    SingleToast.getInstance(MainActivity.this).show("GPS已关闭，速度将无法更新");
                    break;
                default:
                    break;
            }

        }
    };

    // 传感器返回的数据
    @Override
    public void onSensorChanged(SensorEvent event) {
        float[] values = event.values;
        /*ACCELEROMETER_DATA = new StringBuffer();
        ACCELEROMETER_DATA.append("X：").append(new DecimalFormat(".0").format(values[0])).append("\n");
        ACCELEROMETER_DATA.append("Y：").append(new DecimalFormat(".0").format(values[1])).append("\n");
        ACCELEROMETER_DATA.append("Z：").append(new DecimalFormat(".0").format(values[2])).append("\n");
        speed_stv.setCenterString(ACCELEROMETER_DATA);
        */
        ACCELEROMETER_X = Float.parseFloat(new DecimalFormat(".0").format(values[0]));
        ACCELEROMETER_Y = Float.parseFloat(new DecimalFormat(".0").format(values[1]));
        ACCELEROMETER_Z = Float.parseFloat(new DecimalFormat(".0").format(values[2]));

        //用来显示加速度
        if(true){
            test_tv.setText(ACCELEROMETER_X + "\n" +
                    ACCELEROMETER_Y + "\n" +
                    ACCELEROMETER_Z + "\n");
        }

        //不是横屏，即竖屏
        if (!layout_land){
            //判定转弯的触发条件 = 该方向初始值±转弯幅度
            if(ACCELEROMETER_X >= (ACCEL_X + ACCEL_EXTENT)){
                if(FLAG_AUTO_MODE&& current_turn_status!=8){
                    test_tv.append("左转");
                    send("01");
                }
                current_turn_status = 8;
            }else if (ACCELEROMETER_X <= (ACCEL_X - ACCEL_EXTENT)){
                if(FLAG_AUTO_MODE&& current_turn_status!=9){
                    test_tv.append("右转");
                    send("02");
                }
                current_turn_status = 9;
            }else {
                if(FLAG_AUTO_MODE && current_turn_status!=6){
                    test_tv.append("熄灭");
                    send("04");//发送04时同时关闭闪光灯和铃声
                    sh.stop();
                    flp.fickOff();
                }
                current_turn_status = 6;
            }
        }else{//横屏（含左手布局）
            if(ACCELEROMETER_Y >= (ACCEL_Y + ACCEL_EXTENT)){
                if(FLAG_AUTO_MODE&& current_turn_status!=8){
                    test_tv.append("左转");
                    send("02");
                }
                current_turn_status = 8;
            }else if (ACCELEROMETER_Y <= (ACCEL_Y - ACCEL_EXTENT)){
                if(FLAG_AUTO_MODE&& current_turn_status!=9){
                    test_tv.append("左转");
                    send("01");
                }
                current_turn_status = 9;
            }else {
                if(FLAG_AUTO_MODE&& current_turn_status!=6){
                    test_tv.append("熄灭");
                    send("04");
                }
                current_turn_status = 6;
            }
        }

        //在传感器这里“监听”一下车速，用于控制刹车（自动模式打开时）
//        if (informationFlowHelper.flag_stop == 0 && FLAG_AUTO_MODE){
//            try {
//                send("03");
//                //刹车4s后自动复位
//                Thread.sleep(4000);
//                send("04");
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
    }

    //继承传感器接口的必要方法
    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    //权限监听的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode == PERMS_REQUEST_CODE){
            int grantCount = 0;
            for(int grant : grantResults){
                if(grant == PackageManager.PERMISSION_GRANTED){
                    grantCount ++;
                }
            }
            if(grantCount == grantResults.length){
                // 权限获取成功，执行后面的代码
//                locationHelper.init(speed_stv);
//                informationFlowHelper.init(speed_stv, MainActivity.this);
//                informationFlowHelper.getCurrentSpeed();
            }else{
                // 权限获取失败
//                speed_stv.setCenterTopString("无法更新速度");
                SingleToast.getInstance(MainActivity.this).show("权限异常，请检查是否给予全部权限");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onPermissionsAllGranted(int requestCode, List<String> perms, boolean isAllGranted) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    //获取已连接中的设备（从已配对的设备中获取）
    public ArrayList<BluetoothDevice> getConnectionDevices(BluetoothAdapter btAdapter){
        ArrayList<BluetoothDevice> deviceList = new ArrayList<>();
        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
        try {//得到连接状态的方法
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            //打开权限
            method.setAccessible(true);
            int state = (int) method.invoke(btAdapter, (Object[]) null);

            if(state == BluetoothAdapter.STATE_CONNECTED){
                Log.i(TAG,"BluetoothAdapter.STATE_CONNECTED");
                Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
                Log.i(TAG,"devices:"+devices.size());

                for(BluetoothDevice device : devices){
                    Log.i(TAG,"bonded:"+device.getName());
                    Log.i(TAG,"bonded:"+device.getAddress());
                    Log.i(TAG,"bonded:"+device.getUuids());
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    method.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                    if(isConnected){
                        Log.i(TAG,"connected:"+device.getName());
                        Log.i(TAG,"connected:"+device.getAddress());
                        Log.i(TAG,"connected:"+device.getUuids());
                        deviceList.add(device);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return deviceList;
    }


    //初始化蓝牙适配器等
    public boolean BTinit(String DEVICE_ADDRESS) {
        boolean found=false;
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            SingleToast.getInstance(MainActivity.this).show("此设备不支持蓝牙");
        }
        if(!bluetoothAdapter.isEnabled()) {
            Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableAdapter, 0);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        if(bondedDevices.isEmpty()) {
            SingleToast.getInstance(MainActivity.this).show("无配对设备，请先配对");
        } else {
            for (BluetoothDevice iterator : bondedDevices) {
                //根据选择的mac来连接设备
                if(iterator.getAddress().equals(DEVICE_ADDRESS)) {
                    device=iterator;
                    found=true;
                    break;
                }
            }
        }
        return found;
    }
    //连接蓝牙
    public boolean BTconnect() {
        boolean connected=true;
        try {
            socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
            socket.connect();
        } catch (IOException e) {
            e.printStackTrace();
            connected=false;
        }
        if(connected) {
            try {
                outputStream=socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream=socket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return connected;
    }
    //连接设备Part1（HC05）
    public void start(String DEVICE_ADDRESS) {
        if(BTinit(DEVICE_ADDRESS)) {
            if(BTconnect()) {
                targetDeviceConnected=true;
                beginListenForData();
                SingleToast.getInstance(MainActivity.this).show("连接成功");
            }
        }
//        Log.i(TAG, "targetDeviceConnected: " + targetDeviceConnected);
    }
    //连接设备Part2（HC05）-监听数据流
    public void beginListenForData() {
        final Handler handler = new Handler();
        stopThread = false;
        buffer = new byte[1024];
        Thread thread  = new Thread(new Runnable() {
            public void run() {
                while(!Thread.currentThread().isInterrupted() && !stopThread) {
                    try {
                        int byteCount = inputStream.available();
                        if(byteCount > 0) {
                            byte[] rawBytes = new byte[byteCount];
                            inputStream.read(rawBytes);
                            final String string=new String(rawBytes,"UTF-8");
                            handler.post(new Runnable() {
                                public void run() {
                                }
                            });

                        }
                    } catch (IOException ex) {
                        stopThread = true;
                    }
                }
            }
        });

        thread.start();
    }
    //数据输出流
    public void send(String order) {
        byte[] bytes = order.getBytes();
        Log.i(TAG,"try to send(" + order +"):" + pubVari.encodeHex(bytes) + "// " +pubVari.arrayToString(bytes));
        //仅设备连接成功时才发送指令
        if (targetDeviceConnected){
            try {
                outputStream.write(bytes);
                outputStream.flush();
                Log.i(TAG,"success send(" + order +"):");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //监听返回按钮事件，避免加载失败（由于SplashActivity已销毁，因此返回桌面再进入应用时会导致错误）
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
            new QMUIDialog.MessageDialogBuilder(MainActivity.this)
                    .setTitle("提示")
                    .setMessage("确认退出吗？")
                    .addAction("取消", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    })
                    .addAction("确定", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();//一定要记得关闭对话框再关闭MainActivity
                            MainActivity.this.finish();//MainActivity是对话框的父窗口
                        }
                    })
                    .show();
        }
        return false;
    }
}